package com.fei.myback.filter;

import com.fei.myback.service.User.UserServiceImpl;
import com.fei.myback.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt拦截器验证token
 * 继承OncePerRequestFilter 可以确保一次请求只通过一次filter，而不需要重复执行
 */
@Component
@Slf4j
public class JwtFilter extends OncePerRequestFilter {
    @Autowired
    UserServiceImpl userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {


        String authHeader = request.getHeader("Authorization");
        log.info(request.getMethod());
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String authToken = authHeader.substring("Bearer ".length());
            log.info("JwtToken为  "+authToken);
            //从token中获取用户信息
            String username = JwtTokenUtil.parseToken(authToken);
            log.info("访问者用户名：" + username);
            //判断非空，第二个是判断security的内容体的访问者为空
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                UserDetails userDetails = userService.loadUserByUsername(username);
                if (userDetails != null) {
                    //生成security认证信息
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    //再把认证信息设置到认证访问中心
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //最后加入到security中
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        //执行下一个流程点
        filterChain.doFilter(request, response);
    }
}
